﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace Kokomo.Mirror.CliMetadata
{
	class MetadataRowDescriptor : ListItemDescriptor<IMetadataRow>
	{
		public static PropertyDescriptorCollection GetPropertiesForType(
			Type rowType,
			MetadataContainer container
			)
		{
			if ((object)rowType == null) throw new ArgumentNullException("rowType");
			if (container == null) throw new ArgumentNullException("container");

			//object first = this.InnerList.FirstOrDefault();
			//return MetadataRowDescriptor.GetProperties(first.GetType(), this.Container);
			PropertyDescriptorCollection systemDescriptors = TypeDescriptor.GetProperties(rowType);
			List<PropertyDescriptor> descriptors = new List<PropertyDescriptor>(systemDescriptors.Count);

			foreach (PropertyDescriptor systemDescriptor in systemDescriptors)
			{
				descriptors.Add(MetadataRowPropertyDescriptor.GetPropertyDescriptor(systemDescriptor, container));
			}

			return new PropertyDescriptorCollection(descriptors.ToArray());
		}

		public MetadataRowDescriptor(
			IMetadataRow row,
			MetadataContainer container,
			MetadataTypedList owner = null
			)
			: base(row, owner)
		{
			if (row == null) throw new ArgumentNullException("row");
			if (container == null) throw new ArgumentNullException("container");

			this.Row = row;
			this.Container = container;
		}

		public IMetadataRow Row { get; private set; }
		public MetadataContainer Container { get; private set; }

		protected override PropertyDescriptorCollection GetPropertiesCore(Attribute[] attributes)
		{
			return GetPropertiesForType(this.Row.GetType(), this.Container);
		}
		public override string ToString()
		{
			return this.Row.ToString(this.Container);
		}
	}
}
